package com.zxjbyte.yiyi.framework.oss.publisher;

import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.zxjbyte.yiyi.framework.common.util.AuthUtil;
import com.zxjbyte.yiyi.framework.common.util.EventBusUtil;
import com.zxjbyte.yiyi.framework.oss.config.OssProperties;
import com.zxjbyte.yiyi.framework.oss.event.OssRecordAddEvent;
import com.zxjbyte.yiyi.framework.oss.event.OssRecordDeleteEvent;
import com.zxjbyte.yiyi.framework.oss.storage.OssPutResult;
import com.zxjbyte.yiyi.module.system.domain.dto.OssRecordAddDTO;
import com.zxjbyte.yiyi.module.system.domain.dto.OssRecordDelDTO;

import java.util.Date;

/**
 * Oss上传日志记录推送类
 *
 * @Author zhangxingjia
 * @Date 2023/6/26 15:13
 * @Version: 1.0
 */
public class OssRecordPublisher {

    private static OssProperties properties;

    private static OssProperties getProperties(){
        if(properties == null){
            properties = SpringUtil.getBean(OssProperties.class);
        }
        return properties;
    }

    /**
     * 推送Oss上传日志记录
     */
    public static void publishAddEvent(OssPutResult result, String fileSize, String storageService){
        if(!getProperties().getNeedRecord()){
            return;
        }
        OssRecordAddDTO addDto = new OssRecordAddDTO();
        addDto.setStorageService(storageService);
        addDto.setSuffix(FileUtil.getSuffix(result.getOriginalName()));
        addDto.setOriginalName(result.getOriginalName());
        addDto.setFileSize(fileSize);
        addDto.setPath(result.getName());
        addDto.setUrl(result.getLink());
        String userName = AuthUtil.getUserName();
        Date now = new Date();
        addDto.setCreateUser(userName);
        addDto.setCreateTime(now);
        addDto.setUpdateUser(userName);
        addDto.setUpdateTime(now);
        EventBusUtil.asyncPublishEvent(new OssRecordAddEvent(addDto));
    }

    /**
     * 推送Oss删除日志记录
     */
    public static void publishDeleteEvent(String path){
        OssRecordDelDTO delDto = new OssRecordDelDTO();
        delDto.setPath(path);
        delDto.setUpdateUser(AuthUtil.getUserIdAsStr());
        delDto.setUpdateTime(new Date());
        EventBusUtil.asyncPublishEvent(new OssRecordDeleteEvent(delDto));
    }

}
